package com.laicunba.util;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import org.apache.commons.io.IOUtils;

public class HttpUtil {
	/**
	 * 发送POST请求
	 * 
	 * @param url
	 * @param paremeter
	 * @return
	 */
	public static String doPost(String url, Map<String, String> paremeter) throws Exception {
		HttpURLConnection conn = null;
		try {
			URL urlObj = new URL(url);
			conn = (HttpURLConnection) urlObj.openConnection();
			conn.setRequestMethod("POST");
			if (paremeter != null && !paremeter.isEmpty()) {
				StringBuffer sb = new StringBuffer();
				for (String key : paremeter.keySet()) {
					if (paremeter.get(key) == null) {
						continue;
					}
					sb.append("&").append(key).append("=").append(paremeter.get(key));
				}
				conn.setDoOutput(true);
				conn.getOutputStream().write(sb.toString().getBytes("utf-8"));
			}

			if (conn.getResponseCode() == 200) {
				char[] resultChars = IOUtils.toCharArray(conn.getInputStream(), "utf-8");
				return new String(resultChars);
			} else {
				AssertUtil.assertFail("HTTP_ERROR_" + conn.getResponseCode());
			}
		} finally {
			if (conn != null) {
				conn.disconnect();
			}
		}
		return null;
	}

	public static String doGet(String url) throws Exception {
		HttpURLConnection conn = null;
		try {
			URL urlObj = new URL(url);
			conn = (HttpURLConnection) urlObj.openConnection();
			conn.setRequestMethod("GET");
			if (conn.getResponseCode() == 200) {
				char[] resultChars = IOUtils.toCharArray(conn.getInputStream(), "utf-8");
				return new String(resultChars);
			} else {
				AssertUtil.assertFail("HTTP_ERROR_" + conn.getResponseCode());
			}
		} finally {
			if (conn != null) {
				conn.disconnect();
			}
		}
		return null;
	}

	public static String doPost(String url, String body) {
		HttpURLConnection conn = null;
		try {
			URL urlObj = new URL(url);
			conn = (HttpURLConnection) urlObj.openConnection();
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.getOutputStream().write(body.getBytes("utf-8"));
			String content = IOUtils.toString(conn.getInputStream());
			if (conn.getResponseCode() == 200) {
				return content;
			} else {
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			conn.disconnect();
		}
		return null;
	}

}
